// 试卷创建与管理模块
const db = wx.cloud.database();
const paperCollection = db.collection('papers');
const questionCollection = db.collection('questions');
const _ = db.command;

/**
 * 创建试卷
 * @param {Object} paper 试卷数据
 * @returns {Promise} 创建结果
 */
async function createPaper(paper) {
  try {
    // 添加创建时间和更新时间
    paper.createTime = db.serverDate();
    paper.updateTime = db.serverDate();
    
    // 获取当前用户ID作为创建者
    const userInfo = await wx.cloud.callFunction({
      name: 'getUser',
      data: {}
    });
    paper.creator = userInfo.result.openid;
    
    // 默认状态为草稿
    paper.status = paper.status || 'draft';
    
    // 计算总分
    if (paper.questions && paper.questions.length > 0) {
      paper.totalScore = paper.questions.reduce((sum, q) => sum + (q.score || 0), 0);
    } else {
      paper.totalScore = 0;
    }
    
    // 插入数据库
    const result = await paperCollection.add({
      data: paper
    });
    
    return {
      success: true,
      paperId: result._id,
      message: '创建试卷成功'
    };
  } catch (error) {
    console.error('创建试卷失败', error);
    return {
      success: false,
      message: '创建试卷失败: ' + error.message
    };
  }
}

/**
 * 智能组卷
 * @param {Object} params 组卷参数
 * @returns {Promise} 组卷结果
 */
async function generatePaper(params) {
  try {
    const { subject, difficulty, totalScore, questionTypes, knowledgePoints } = params;
    
    // 调用云函数进行智能组卷
    const result = await wx.cloud.callFunction({
      name: 'paper-generate',
      data: {
        subject,
        difficulty,
        totalScore,
        questionTypes,
        knowledgePoints
      }
    });
    
    return {
      success: true,
      ...result.result
    };
  } catch (error) {
    console.error('智能组卷失败', error);
    return {
      success: false,
      message: '智能组卷失败: ' + error.message
    };
  }
}

/**
 * 获取试卷详情
 * @param {String} paperId 试卷ID
 * @returns {Promise} 试卷详情
 */
async function getPaperDetail(paperId) {
  try {
    // 获取试卷基本信息
    const paperRes = await paperCollection.doc(paperId).get();
    const paper = paperRes.data;
    
    if (!paper) {
      return {
        success: false,
        message: '试卷不存在'
      };
    }
    
    // 获取试题详情
    const questionIds = paper.questions.map(q => q.questionId);
    const questionsRes = await questionCollection.where({
      _id: _.in(questionIds)
    }).get();
    
    // 将题目详情与分值合并
    const questionsMap = {};
    questionsRes.data.forEach(q => {
      questionsMap[q._id] = q;
    });
    
    const questions = paper.questions.map(q => {
      return {
        ...questionsMap[q.questionId],
        score: q.score
      };
    });
    
    return {
      success: true,
      paper: {
        ...paper,
        questionDetails: questions
      }
    };
  } catch (error) {
    console.error('获取试卷详情失败', error);
    return {
      success: false,
      message: '获取试卷详情失败: ' + error.message
    };
  }
}

/**
 * 查询试卷列表
 * @param {Object} params 查询参数
 * @returns {Promise} 查询结果
 */
async function getPaperList(params = {}) {
  try {
    const { subject, status, keyword, creatorOnly = true, page = 1, size = 20 } = params;
    
    let query = paperCollection;
    
    // 构建查询条件
    if (subject) {
      query = query.where({
        subject: subject
      });
    }
    
    if (status) {
      query = query.where({
        status: status
      });
    }
    
    // 只查询当前用户创建的试卷
    if (creatorOnly) {
      const userInfo = await wx.cloud.callFunction({
        name: 'getUser',
        data: {}
      });
      query = query.where({
        creator: userInfo.result.openid
      });
    }
    
    if (keyword) {
      query = query.where({
        title: db.RegExp({
          regexp: keyword,
          options: 'i'
        })
      });
    }
    
    // 获取总数
    const countResult = await query.count();
    const total = countResult.total;
    
    // 分页查询
    const result = await query
      .orderBy('createTime', 'desc')
      .skip((page - 1) * size)
      .limit(size)
      .get();
    
    return {
      success: true,
      papers: result.data,
      total,
      page,
      size
    };
  } catch (error) {
    console.error('查询试卷失败', error);
    return {
      success: false,
      message: '查询试卷失败: ' + error.message
    };
  }
}

/**
 * 更新试卷
 * @param {String} paperId 试卷ID
 * @param {Object} data 更新数据
 * @returns {Promise} 更新结果
 */
async function updatePaper(paperId, data) {
  try {
    // 添加更新时间
    data.updateTime = db.serverDate();
    
    // 如果更新了试题，重新计算总分
    if (data.questions && data.questions.length > 0) {
      data.totalScore = data.questions.reduce((sum, q) => sum + (q.score || 0), 0);
    }
    
    // 更新数据库
    await paperCollection.doc(paperId).update({
      data
    });
    
    return {
      success: true,
      message: '更新试卷成功'
    };
  } catch (error) {
    console.error('更新试卷失败', error);
    return {
      success: false,
      message: '更新试卷失败: ' + error.message
    };
  }
}

/**
 * 发布试卷
 * @param {String} paperId 试卷ID
 * @returns {Promise} 发布结果
 */
async function publishPaper(paperId) {
  try {
    // 获取试卷信息
    const paperRes = await paperCollection.doc(paperId).get();
    const paper = paperRes.data;
    
    if (!paper) {
      return {
        success: false,
        message: '试卷不存在'
      };
    }
    
    // 校验试卷信息
    if (!paper.title) {
      return {
        success: false,
        message: '试卷标题不能为空'
      };
    }
    
    if (!paper.questions || paper.questions.length === 0) {
      return {
        success: false,
        message: '试卷中至少需要一道题目'
      };
    }
    
    // 更新试卷状态为已发布
    await paperCollection.doc(paperId).update({
      data: {
        status: 'published',
        updateTime: db.serverDate()
      }
    });
    
    // 生成唯一考试码
    const examCode = await generateExamCode();
    
    return {
      success: true,
      examCode,
      message: '试卷发布成功'
    };
  } catch (error) {
    console.error('发布试卷失败', error);
    return {
      success: false,
      message: '发布试卷失败: ' + error.message
    };
  }
}

/**
 * 生成唯一考试码
 * @returns {Promise<string>} 考试码
 */
async function generateExamCode() {
  // 生成6位随机数字字母组合
  const characters = 'ABCDEFGHJKLMNPQRSTUVWXYZ23456789';
  let code = '';
  for (let i = 0; i < 6; i++) {
    code += characters.charAt(Math.floor(Math.random() * characters.length));
  }
  
  // 检查是否已存在
  const codeCheckRes = await db.collection('exam_codes').where({
    code: code,
    expireTime: _.gt(db.serverDate())
  }).count();
  
  if (codeCheckRes.total > 0) {
    // 递归重新生成
    return generateExamCode();
  }
  
  // 保存考试码
  const expireTime = new Date();
  expireTime.setDate(expireTime.getDate() + 7); // 默认7天有效期
  
  await db.collection('exam_codes').add({
    data: {
      code,
      createTime: db.serverDate(),
      expireTime,
      status: 'active'
    }
  });
  
  return code;
}

/**
 * 删除试卷
 * @param {String} paperId 试卷ID
 * @returns {Promise} 删除结果
 */
async function deletePaper(paperId) {
  try {
    // 检查试卷是否有人答题
    const checkResult = await wx.cloud.callFunction({
      name: 'checkPaperUsage',
      data: {
        paperId
      }
    });
    
    if (checkResult.result.isUsed) {
      return {
        success: false,
        message: '该试卷已有人答题，无法删除'
      };
    }
    
    // 删除试卷
    await paperCollection.doc(paperId).remove();
    
    return {
      success: true,
      message: '删除试卷成功'
    };
  } catch (error) {
    console.error('删除试卷失败', error);
    return {
      success: false,
      message: '删除试卷失败: ' + error.message
    };
  }
}

module.exports = {
  createPaper,
  generatePaper,
  getPaperDetail,
  getPaperList,
  updatePaper,
  publishPaper,
  deletePaper
}; 